package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"perfect-admin/service"
	"strconv"
	"strings"
)

func GetRoleList(c *gin.Context)  {
	roles, err := service.GetRoleList()
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取角色列表成功", "data": roles})
	}
	return
}

func GetAllRoleMenuTree(c *gin.Context)  {
	var queryInfo request.QueryInfo
	if err := c.ShouldBind(&queryInfo); err!=nil{
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	roles, total, err := service.GetAllRoleMenuTree(queryInfo)
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取角色列表成功", "data": map[string]interface{}{
			"roles": roles,
			"total": total,
		}})
	}
	return
}

func AddOneRole(c *gin.Context)  {
	var role model.SysRole
	if err := c.BindJSON(&role); err != nil{
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.AddOneRole(role)
	if err!=nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "添加角色成功", "data": nil})
	}
	return
}

func UpdateRole(c *gin.Context)  {
	var role model.SysRole
	if err := c.BindJSON(&role); err != nil{
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.UpdateRole(role)
	if err!=nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "修改角色信息成功", "data": nil})
	}
	return
}

func DeleteRole(c *gin.Context)  {
	role_id, ok := c.GetQuery("role_id")
	roleId, err := strconv.Atoi(role_id)
	if !ok || err!= nil{
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err = service.DeleteRole(roleId)
	if err!=nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "删除角色成功", "data": nil})
	}
	return
}

func DeleteRoleRight(c *gin.Context)  {
	role_id, ok1 := c.GetQuery("role_id")
	menu_ids, ok2 := c.GetQuery("menu_ids")
	roleId, err1 := strconv.Atoi(role_id)
	menuIds := strings.Split(menu_ids, "-")
	if !ok1 || !ok2 || err1 != nil || len(menu_ids) < 1{
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.DeleteRoleRight(roleId, menuIds)
	if err!=nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	}else {
		menu_tree, _, _ := service.GetRoleMenuTree(roleId)
		c.JSON(http.StatusOK, gin.H{"msg": "删除角色权限成功", "data": menu_tree})
	}
	return
}

func AllotMenus(c *gin.Context)  {
	menu_ids, ok := c.GetPostForm("menu_ids")
	role_id, ok1 := c.GetPostForm("role_id")
	menu_id_list := strings.Split(menu_ids, ",")
	roleId, _ := strconv.Atoi(role_id)
	if !ok || !ok1{
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.UpdateRoleMenus(menu_id_list, roleId)
	if err!=nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "更新角色权限成功", "data": nil})
	}
	return
}